# -*- coding: utf-8 -*-
#函数接收变量
from __future__ import unicode_literals
from math import sqrt
def add (x,y,f):
    return f(x)+f(y)
print add(-5,9,abs)
#14
#利用add(x,y,f)函数，计算平方根
print add(4,9,sqrt)
#5.0
"""
也可以这样
import math
def add(x, y, f):
    return f(x) + f(y)
print add(25, 9, math.sqrt)
"""
s = ur'''Python的Unicode字符串U支持"中文",
"日文",
"韩文"等多种语言'''
print s[s.index('U')]#打印s

#例如，对于list [1, 2, 3, 4, 5, 6, 7, 8, 9]
#如果希望把list的每个元素都作平方，就可以用map()函数：
def f(x):
    return x*x
print map(f, [1,2,3,4])
#[1, 4, 9, 16]

def format_name(x):
    return x[0].upper()+x[1:].lower()
print map(format_name, ['adam','LISA','barT'])
#[u'Adam', u'Lisa', u'Bart']

def f1(x,y):
    return x+y
print reduce(f1, [1,3,4],8)
#16

def f2(x,y):
    return x*y
print reduce(f2, [2, 4, 5, 7, 12])
#3360

def f3(x):
    if x==3 or x==4:
        return False
    else:
        return True

print filter(f3,[1,2,3,4,5,6,7])
#sorted高阶函数
print 'sorted高阶函数'
print sorted([36, 5, 12, 9, 21])
def compareTo(x,y):
    if(x>y):
        return -1
    elif x<y:
        return 1
    else:
        return 0
#sorted自定义倒序
print sorted([36, 5, 12, 9, 21],compareTo)
print sorted(['bob', 'about', 'Zoo', 'Credit'])

#返回函数
print '返回函数'

def fc():
    print 'call f()...'
    # 定义函数g:
    def g():
        print 'call g()...'
        return "i am g"
    # 返回函数g:
    return g

x = fc()
#print x
print x()

def calc_prod(list1):
    def lazy_prod():
        return reduce(f2, list1,1)
    return lazy_prod
#
print calc_prod([1,2,3,4])
#
cw = calc_prod([1,2,3,4])
print cw()
#python闭包
print 'python闭包'
def count():
    fs = []
    for i in range(1, 4):
        def f():
            return i*i
        fs.append(f)
    return fs
print count()

f1, f2, f3 = count()
print f1,f2,f3
def count1():
    fs = []
    for i in range(1, 4):
        def f():
            return i*i
        fs.append(f())
    return fs
print count()

f1, f2, f3 = count1()
print f1,f2,f3
#匿名函数
def is_not_empty(s):
    return s and len(s.strip()) > 0
filter(is_not_empty, ['test', None, '', 'str', '  ', 'END'])
f5 = filter(lambda x : x and len(x.strip()) > 0 ,['test', None, '', 'str', '  ', 'END'])
print f5

str1 = '_Person__count'
print str1.find("__")
str1 = '__Personcount'
print str1.find("__")

def getMyselfShuxing(List):
    rList=[]
    for str1 in list:
        if str1.find("__") > 0:#str.find("__")找到目标字符串的下表，没有则返回-1
            continue
        else:
            rList.append(str1)
    return rList

print 'decorator修饰'
#*args是非关键字参数，用于元组，**kw是关键字参数，用于字典
def log(f):
    def fn(*args,**kw):
        print "*args的值是:", 
        print 'call ' + f.__name__ + '()...'
        s = f(*args,**kw)
        return s
    return fn

@log
def factorial(n):
    s = reduce(lambda x,y: x*y, range(1, n+1))
    return s

print factorial(3)

import time
def performance(f):
    def fn(*args, **kw):
        t1 = time.time()
        r = f(*args, **kw)
        t2 = time.time()
        print 'call %s() in %fs' % (f.__name__, (t2 - t1))
        return r
    return fn

@performance
def factorial1(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
print factorial1(10)

print '带参数的decorator修饰'
def logInput(prefix):
    def log_decorator(f):
        def wrapper(*args, **kw):
            print '[%s] %s()...' % (prefix, f.__name__)
            return f(*args, **kw)
        return wrapper
    return log_decorator

@logInput('DEBUG')
def test():
    pass
print test()

def performance1(unit):
    def performance_decorator(f):
        def fn(*args, **kw):
            t1 = time.time()
            r = f(*args, **kw)
            t2 = time.time()
            t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
            print 'call %s() in %f %s' % (f.__name__, t, unit)
            return r
        return fn
    return performance_decorator

@performance1('ms')
def factorial2(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
print factorial2(10)

import functools
def performance3(unit):
    def perf_decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kw):
            t1 = time.time()
            r = f(*args, **kw)
            t2 = time.time()
            t = (t2 - t1) * 1000 if unit=='ms' else (t2 - t1)
            print 'call %s() in %f %s' % (f.__name__, t, unit)
            return r
        return wrapper
    return perf_decorator

@performance3('ms')
def factorial3(n):
    return reduce(lambda x,y: x*y, range(1, n+1))
print factorial3.__name__

print "偏函数"
sorted_ignore_case = functools.partial(sorted, cmp=lambda s1, s2: cmp(s1.upper(), s2.upper()))
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])

print "模块"
import math,logging
print math.log(10)   # 调用的是math的log函数
print logging.log(10, 'something')   # 调用的是logging的log函数

from math import log
from logging import log as logger   # logging的log现在变成了logger
print log(10)   # 调用的是math的log
logger(10, 'import from logging')   # 调用的是logging的log

import os
print os.path.isdir(r'/Users/wangjunjie/Documentst')
print os.path.isfile(r'/Users/wangjunjie/Documents/登录注册.graffle')

#from __future__ import unicode_literals
s = '''Python的Unicode字符串支持"中文",
"日文",
"韩文"等多种语言'''
print s
s = 'am I an unicode?'
print isinstance(s, unicode)

